<?php
require_once( PHP_PATH . 'common.php' );

$template->title = "View Your Expense  Report";
$template->welcomeMsg = "View Your Expense  Report";

// get year list
$selectedYear = isset( Url::$pageVars[ 'GETPOST' ][ 'y' ] ) ? Url::$pageVars[ 'GETPOST' ][ 'y' ] : 0;
$thisYear = date( 'Y' );
$years = array();
for( $y=$thisYear; $y >= 2014; $y-- ){
	$years[] = array(
		'text' => $y, 'value' => $y, 'selected' => $y == $selectedYear ? 'selected' : ''
	);
}
$template->years = $years;
// get all months list or a year
$selectedMonth = isset( Url::$pageVars[ 'GETPOST' ][ 'm' ] ) ? Url::$pageVars[ 'GETPOST' ][ 'm' ] : 0;
$months = array();
for( $m=1; $m <= 12; $m++ ){
	$months[] = array(
		'text' => date( "M", mktime( 0, 0, 0, $m, 1, $thisYear ) ), 
		'value' => $m, 'selected' => $m == $selectedMonth ? 'selected' : ''
	);
}
$template->months = $months;
// get user's teams
$teamId = isset( Url::$pageVars[ 'GETPOST' ][ 'tid' ] ) ? Url::$pageVars[ 'GETPOST' ][ 'tid' ] : 0;
$template->teams = Utility::getUserTeams( $teamId );
// get selected members list
$members = isset( Url::$pageVars[ 'GETPOST' ][ 'members' ] ) ? Url::$pageVars[ 'GETPOST' ][ 'members' ] : array();
// make final call to get all expenses
$expenses = $paging = array();
$groupId = isset( Url::$pageVars[ 'GETPOST' ][ 'gid' ] ) ? Url::$pageVars[ 'GETPOST' ][ 'gid' ] : 0;
$memberId = isset( Url::$pageVars[ 'GETPOST' ][ 'uid' ] ) ? Url::$pageVars[ 'GETPOST' ][ 'uid' ] : 0;
if( is_numeric( $teamId ) && is_numeric( $selectedMonth ) && is_numeric( $selectedYear ) ){
	if( $teamId > 0 && $selectedMonth > 0 && $selectedYear > 0 ){
		$whereClause = array( 
			'teamId' => $teamId, 'members' => $members, 
			'memberId' => $memberId, 'groupId' => $groupId,
			'month' => $selectedMonth, 'year' => $selectedYear 
		);
		$PageNo = isset( Url::$pageVars['GETPOST']['page'] ) ? Url::$pageVars['GETPOST']['page'] : 1;
		$teamExpenses = ExpenseUtility::getTeamExpensesReport( $whereClause, $PageNo );
		$expenses = $teamExpenses[ 'expenses' ];
		$groupId = $teamExpenses[ 'groupId' ];
		$memberId = $teamExpenses[ 'memberId' ];
		$paging = $teamExpenses[ 'paging' ];
	}
}
$template->expenses = $expenses;
$template->paging = $paging;
// get all team members with selected members
$template->members = $members = $teamId > 0 ? Utility::getTeamMembersAndGroupMembers( $teamId, $groupId, $memberId ) : array();
// if selected members presnt then show else hide the whole row
$template->membersShow = count( $members ) > 0 ? '' : 'none';
